package com.vehicle.admin.web.common.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Controller
@RequestMapping("/common")
public class CommonController extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(CommonController.class);

    @RequestMapping("/404")
    public ModelAndView _404(HttpServletRequest request) {
        ModelAndView view = new ModelAndView("/common/404");
        return view;
    }

    @RequestMapping("/500")
    public ModelAndView _500(HttpServletRequest request) {
        ModelAndView view = new ModelAndView("/common/500");

        Throwable t = (Throwable) request.getAttribute("javax.servlet.error.exception");

        String defaultMessage = "未知异常";

        if (Objects.isNull(t)) {
           view.addObject("line",defaultMessage);
           view.addObject("clazz",defaultMessage);
           view.addObject("methodName",defaultMessage);
           return view;
        }

        String message=t.getMessage();
        StackTraceElement[] stack=t.getStackTrace();
        view.addObject("message",message);
        if(Objects.nonNull(stack)&&stack.length>0){
            StackTraceElement element=stack[0];
            int line=element.getLineNumber();
            String clazz=element.getClassName();
            String fileName=element.getFileName();

            String methodName=element.getMethodName();
            view.addObject("line",line);
            view.addObject("clazz",clazz);
            view.addObject("methodName",methodName);

            LOGGER.error("an error occurred. line:{},clazz:{},fileName:{},methodName:{}",line,clazz,fileName,methodName);
        }
        return view;
    }

    @RequestMapping(value = "/unauthorized",method = RequestMethod.GET)
    public ModelAndView unauthorized(){
        return new ModelAndView("/common/unauthorized");
    }
}
